package cn.hdu.liang.core.controller;

import cn.hdu.liang.common.web.session.SessionProvider;
import cn.hdu.liang.core.bean.BuyCart;
import cn.hdu.liang.core.bean.BuyItem;
import cn.hdu.liang.core.bean.order.Order;
import cn.hdu.liang.core.bean.product.Sku;
import cn.hdu.liang.core.bean.user.Buyer;
import cn.hdu.liang.core.service.order.OrderService;
import cn.hdu.liang.core.service.product.SkuService;
import cn.hdu.liang.core.web.Constants;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 提交订单 前台
 */
@Controller
public class FrontOrderController {

    //提交订单
    @Autowired
    private OrderService orderService;
    @Autowired
    private SessionProvider sessionProvider;
    @Autowired
    private SkuService skuService;

    //提交订单
    @RequestMapping(value = "/buyer/confirmOrder.shtml")
    public String confirmOrder(Order order, HttpServletRequest req, HttpServletResponse resp) {
        //1:接收前台传四个参数

        ObjectMapper om = new ObjectMapper();
        om.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

        BuyCart buyCart = null;
        Cookie[] cookies = req.getCookies();
        if(null != cookies && cookies.length > 0) {
            for(Cookie c : cookies) {
                if(Constants.BUYCART_COOKIE.equals(c.getName())) {
                    //如果有了  就使用此购物车
                    String value = c.getValue();//
                    //
                    try {
                        buyCart = om.readValue(value, BuyCart.class);
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }

        //装购物车装满
        List<BuyItem> its = buyCart.getItems();
        for(BuyItem item : its) {
            Sku s = skuService.getSkuByKey(item.getSku().getId());
            item.setSku(s);
        }

        Buyer buyer = (Buyer) sessionProvider.getAttribute(req, Constants.BUYER_SESSION);
        //用户Id
        order.setBuyerId(buyer.getUsername());
        //保存订单   订单详情  二张表
        orderService.addOrder(order, buyCart);
        //清空购物车
        Cookie cookie = new Cookie(Constants.BUYCART_COOKIE, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        resp.addCookie(cookie);

        return "product/confirmOrder";
    }

}
